

var firstloadBool = true;
var preRefSco;




var curriculumViewModel = new CurriculumViewModel();
function initialize(){
	console.log("--------> BODY loaded");
    ko.applyBindings(curriculumViewModel);   
   // getSchoolTeachers(availableTags);
  
}


// -----------------------Binding For Accordian-------------------------
    
    ko.bindingHandlers.jqAccordion = {    
        init: function (element, valueAccessor) {    
            var options         = valueAccessor(),    
            accordianOptions    = options.options; 
            jQuery(element).accordion(accordianOptions);  
            jQuery(element).bind("valueChanged", function () {    
                ko.bindingHandlers.jqAccordion.update(element, valueAccessor);    
            });  
           
        },
        update: function (element, valueAccessor) {
            var options = valueAccessor(),
                accordianOptions = options.options,
                dependency = ko.utils.unwrapObservable(options.updateOn);
            jQuery(element).accordion('destroy').accordion(accordianOptions);
        }
    };  
    
  

// -----------------------Binding For Tabs-------------------------
ko.bindingHandlers.jqTabs = {
    init: function(element, valueAccessor) {
        var options = valueAccessor() || {};
        setTimeout( function() { $(element).tabs(options); }, 1000);
    }
};

//---------------------------------------------------------------

function CurriculumViewModel() {
    
        var self                            = this;   
        self.title                          = "Version New";
        self.windowMode                     = "";        
        
        self.curriculumArr    	            = ko.observableArray([]);  
        self.teacherArr						= ko.observableArray([]);  
        self.planArr					    = ko.observableArray([]);
        self.label                          = ko.observable('dialog test');
        self.isOpen                         = ko.observable(false);    
        self.currentContent                 = ko.observable();        
        self.itemForEditing         		= ko.observable();   
        self.selectedItem           		= ko.observable();
        self.currentPlanVo					= ko.observable();
        self.teacherNameVal					= ko.observable();
        self.selectedUserId   				= ko.observable();
        self.filteredTeacherArr				= ko.observableArray([]);  
  
        
     //-----------------BO Loading Curriculum JSON---------------------------------   
       
		var teacherJsonData                       = $.getJSON(teacherUrl, {returnformat : 'json'}, function(teacherData) {
		        var mappedTeacherData              = jQuery.map(teacherData, function(item) {
		       //console.log("teacherJsonData----------",item)
		        return new TeacherVo(item)
		        
        	});
	        self.teacherArr(mappedTeacherData);
	        
	        
			    teacherJsonData.done(function() { console.log( "second success" ); }) 
			    teacherJsonData.fail(function() { console.log( "error" ); }) 
			    teacherJsonData.always(function() { console.log( "--mappedTeacherData complete--" ); });
		
		 
		
		
		 		var curriculumJsonData                       = $.getJSON(mainUrl, {returnformat : 'json'}, function(curriculumData) {
				        var mappedCurriculumData              = jQuery.map(curriculumData, function(item) {
				        return new CurriculumVO(item,self.teacherArr())
				        //console.log("curriculumJsonData----------",item)
		        	});
			        self.curriculumArr(mappedCurriculumData);
			        //console.log("curriculumJsonData----------",mappedCurriculumData)
		        
		    	}); 
			    curriculumJsonData.done(function() { //console.log( "second success" ); 
			    }) 
			    curriculumJsonData.fail(function() { console.log( "error" ); }) 
			    curriculumJsonData.always(function() { //console.log( "--mappedCurriculumData complete--" ); 
			    
			    });      
    	});
    
   //-----------------EO Loading Curriculum JSON---------------------------------     
   
    	
             
   		self.openViewPlanModel   = function(item){
   			console.log("openviewplanmodel", self.curriculumArr())
   			
   			currCeGradeId=this.ceGradeId();
		    currSubjectId=this.subjectId();
		    		    
            self.windowMode="add";          
		 		var planJsonData                       = $.getJSON(planUrl, {returnformat : 'json'}, function(planData) {
				        var mappedPlanData              = jQuery.map(planData, function(item) {
				        return new PlanVO(item,self.currentPlanVo)
				      //  console.log("planJsonData----------",item)
		        	});
			        self.planArr(mappedPlanData);
			        //console.log("planJsonData----------",mappedPlanData)
			        var settings = {autoReinitialise: true};
					var pane = $('.scroll-pane16')
					pane.jScrollPane(settings);
			        console.log("self.planTermId",self.currentPlanVo())
		        
		    	}); 
			    planJsonData.done(function() {
			    	
			    	
			    	
			    	 console.log( "second success--" );console.log("self.planTermId1",self.currentPlanVo()) }) 
			    planJsonData.fail(function() { console.log( "error" );console.log("self.planTermId2",self.currentPlanVo()) }) 
			    planJsonData.always(function() { console.log( "--mappedPlanData complete--" );console.log("self.planTermId3",self.currentPlanVo()) });
			    
			    
			   
			    
          
          var viewPlanDialog =  $( "#view-Plan" ).dialog( "open" );
          viewPlanDialog.dialog("option", "position", "center");
           
            $( "#teacherNameDialog" ).empty();
            
           $( "#teacherNameDialog" ).text( item.teacherName() );               
           $('#view-Plan').dialog('option', 'title', item.subjectTitle());    
        }
        
        self.closeView = function(){ firstloadBool = true;}	
        
        self.changeTeacherModel	=	function(item){
        	currCeGradeId=this.ceGradeId();
		    currSubjectId=this.subjectId();
		    self.teacherNameVal(item.teacherName())
		    var filteredTeacherDataUrl = filteredTeacherUrl +"&ceGradeId="+currCeGradeId+"&subjectId="+currSubjectId;
		    var filteredTeacherData                       = $.getJSON(filteredTeacherDataUrl, {returnformat : 'json'}, function(teacherData) {
				        var mappedfilteredTeacherData              = jQuery.map(teacherData, function(item) {
				        return new FilteredTeacherVo(item)
				        console.log("filteredTeacherData----------",item)
		        	});
			        self.filteredTeacherArr(mappedfilteredTeacherData);
			       // console.log("filteredTeacherList----------",self.filteredTeacherArr())			       
		        
		    	}); 
			    filteredTeacherData.done(function() { console.log( "second success filteredTeacherData" ) }) 
			    filteredTeacherData.fail(function() { console.log( "error filteredTeacherData" )}) 
			    filteredTeacherData.always(function() { console.log( "--mappedPlanData complete--filteredTeacherData" )});
		    
			var assignRollDialog = $( "#assign-roll" ).dialog( "open" );	 
        	assignRollDialog.dialog("option", "position", "center");
        }
        
        
        self.selectedUserId.subscribe(function(value) 
        {
	       	currChangeTeacherId = value;
			console.log("selectedUserId:", value);		
		});
	
       
        self.saveChangedTeacher = function()
        {         
	    	var completeChangeTeacherUrl = changeTeacherUrl+'&ceGradeId='+currCeGradeId+'&subjectId='+currSubjectId+'&teacherId='+currChangeTeacherId;
	    	changeTeacher(completeChangeTeacherUrl);        	
        }     
}


function PlanVO(data,currentPlanVo) {
    var self = this; 
    //console.log("PlanVO",data)
    self.termId                           				=   ko.observable(data.termId);       
    self.termTitle                              		=   ko.observable(data.termTitle);
    self.sectionId                                		=   ko.observable(data.sectionId);  
    self.startDate										=	ko.observable(data.startDate);   
    self.endDate										=	ko.observable(data.endDate);  
    self.planContentArr									=   ko.observableArray([]); 
     
    
     
     
    self.titleDate										=	ko.computed(function() {
        var _titleDate;
      	var datFor1=	self.startDate().split("-");
        var datFor2=	self.endDate().split("-");
		if(datFor1.length < 2)
		{
			var dt1=new Date();
			datFor1[2]=dt1.getDate();
			datFor1[1]=dt1.getMonth();
			datFor1[0]=dt1.getFullYear();
		}
		
		if(datFor2.length < 2)
		{
			var dt2=new Date();
			datFor2[2]=dt2.getDate();
			datFor2[1]=dt2.getMonth();
			datFor2[0]=dt2.getFullYear();
		}
		
		
		
	   	_titleDate = datFor1[2]+"-"+datFor1[1]+"-"+datFor1[0] + " to " + datFor2[2]+"-"+datFor2[1]+"-"+datFor2[0] ;    
        return _titleDate;   
    }, this);   
    
   currentPlanVo(self); 
    
   
   if(firstloadBool)
    {
    	
    	
    	
    
		jQuery('#tabid').css("background", "url(/ce-static-testedge/common/images/tabActiveBg.png) repeat-x bottom");
	
		
    	
    	
    	
    		currTermId=self.termId ();
    		var currPlanDataUrl = planDataUrl+ "&termId="+currTermId+"&ceGradeId="+currCeGradeId+"&subjectId="+currSubjectId
	    	
	    	 //console.log("currPlanDataUrl",currTermId,"    ",currCeGradeId,"    ",currSubjectId,"    ",planDataUrl)
	    	 
		 
			 var planContentJsonData                       = $.getJSON(currPlanDataUrl, {returnformat : 'json'}, function(planContentData) {
				        var mappedPlanContentData              = jQuery.map(planContentData, function(item) {
				        return new PlanContentVO(item)
				        //console.log("planContentJsonData----------",item)
		        	});
			        self.planContentArr(mappedPlanContentData);
			      //  console.log("planContentArr----------",self.planContentArr())
		        
		    	}); 
			    planContentJsonData.done(function() { console.log( "second success" ); }) 
			    planContentJsonData.fail(function() { console.log( "error" ); }) 
			    planContentJsonData.always(function() { console.log( "--mappedPlanData complete--" );
			    
			    currentPlanVo(self); 
	    		//console.log("currentPlanVo().planContentArr()",currentPlanVo().planContentArr())
			    
			     });
    	
    	 firstloadBool = false; 
    	
    }
   
   
  
   
    self.changeTabModel = function()
	{
	    	
	    	 currTermId=self.termId ();
	    	 
	    	 console.log("---------currTermId---------",currTermId)
	    	 
	    	 
	    	 var currPlanDataUrl = planDataUrl+ "&termId="+currTermId+"&ceGradeId="+currCeGradeId+"&subjectId="+currSubjectId
	    	
	    //	console.log("currPlanDataUrl",currTermId,"    ",currCeGradeId,"    ",currSubjectId,"    ",planDataUrl, "self.termTitle   ",self.termTitle()   )
	    	 
			 var planContentJsonData                       = $.getJSON(currPlanDataUrl, {returnformat : 'json'}, function(planContentData) {
				        var mappedPlanContentData              = jQuery.map(planContentData, function(item) {
				        console.log("planContentJsonData----------",item)
				        return new PlanContentVO(item)
				        
		        	});
			        self.planContentArr(mappedPlanContentData);
			        console.log("planContentArr----------",mappedPlanContentData)
		        
		    	}); 
			    planContentJsonData.done(function() { console.log( "second success" ); }) 
			    planContentJsonData.fail(function() { console.log( "error" ); }) 
			    planContentJsonData.always(function() { console.log( "--mappedPlanData complete--" );
			    
			    currentPlanVo(self); 
	    		//console.log("currentPlanVo().planContentArr()",currentPlanVo().planContentArr()[0].chapterTitle())
			    
			     });
			    
			    
	}
	
	
   
 
 
 
 
 
 
 }

function PlanContentVO(data) {
    var self = this; 
  //  console.log("PlanContentVO",data)
    self.totalTestPeriod                          		=   ko.observable(data.totalTestPeriod);    
    self.chapterTitle                           		=   ko.observable(data.chapterTitle);       
    self.subjectId                              		=   ko.observable(data.subjectId);
    self.termId                                			=   ko.observable(data.termId);
    self.totalTeachingPeriod                       		=   ko.observable(data.totalTeachingPeriod);    
    self.aypChapterId                           		=   ko.observable(data.aypChapterId);       
    self.ceGradeId                              		=   ko.observable(data.ceGradeId);
    self.chapterId                                		=   ko.observable(data.chapterId);
    self.chapterOrderNo                              	=   ko.observable(data.chapterOrderNo);   
   	self.curriculumPlanXml                              =   ko.observable(data.curriculumPlanXml);   
   	self.versionComments                              	=   ko.observable(data.versionComments);     
   	self.contents										=	ko.observable();      
	self.objective										=	ko.observable();            
	self.outcome										=	ko.observable();          	
   	
   	
	
	self.loadChapterData	=	function()
	{
		var chapterDataUrl = baseurl+AYP_GET_CHAPTER_CURR_PLAN_JSON+ "&aypChapterId="+ self.aypChapterId();	
	console.log("3333self.loadChapterData",chapterDataUrl)
	
	
		var chapterJsonData								= $.getJSON(chapterDataUrl, {returnformat : 'json'}, function(chapterData) 
		{		
			var tempArr = new Array()
			tempArr =  chapterData.split("^=^");     
			console.log("chapterJsonData----------",tempArr)    
			self.contents(tempArr[0]);   	        
			self.objective(tempArr[1]);         
			self.outcome(tempArr[2]);	
		}); 
		chapterJsonData.done(function() { console.log( "second success" ); }) 
		chapterJsonData.fail(function() { console.log( "error" ); }) 
		chapterJsonData.always(function() { console.log( "--mappedPlanData complete--" );});		  
	}  	
 }

function TeacherVo(data) {
    var self = this; 
    self.userId                           				=   ko.observable();
	self.title                              		    =   ko.observable();	
    self.firstName                              		=   ko.observable();
    self.middleName                                		=   ko.observable();
    self.lastName                              			=   ko.observable();
  
    self.cache = function() {};
    self.update(data)    
 }
 
 function FilteredTeacherVo(data) {
    var self = this; 
    self.userId   										=   ko.observable(data.userId);  
    self.title	                        				=   ko.observable(data.title);       
    self.firstName                              		=   ko.observable(data.firstName);
    self.middleName                                		=   ko.observable(data.middleName);
    self.lastName    									=   ko.observable(data.lastName);
    
    self.fullName										=	ko.computed(function() {
            	
         var _fullName =  self.title()+" "+self.firstName()+" "+self.lastName();
        return  _fullName;   
    }, this);   
    
    
    
    
 }
 
 
 
 
//-----------------------------------------------------------------------------




function CurriculumVO(data,teacherArr) {
    var self = this;   
  
    
    self.ceGradeId                              	=   ko.observable();  
    self.gradeTitle                           		=   ko.observable();
    self.data                        				=   ko.observableArray();
    self.status										=	ko.computed(function() {
        var _status = "Completed";
        for(var i=0;i<self.data().length;i++)
        {
        	console.log(i,"self.status",self.data()[i].planStatus()	)
        	
        	if(!self.data()[i].planStatus()||self.data()[i].planStatus()==0)
        	{
        		console.log(i,"Inside If self.status",self.data()[i].planStatus()	)
        		_status = "Not Completed"
        	}
        	if(self.data()[i].planStatus()==1)
        	{
        		console.log(i,"Inside If self.status",self.data()[i].planStatus()	)
        		_status = "Not Completed"
        	}
        
        }          
          
        return _status;   
    }, this);   
       
    
     self.applyCssKo = function() {
     	console.log( "self.styling ")       	
     	
        if(self.status() =="Completed")
        {
        	return 'statusComplete';
        } 
        else
        {
        	return 'statusPending';
        } 
    }    
 
    self.cache = function() {};
    self.update(data,teacherArr)   
 }
 
 
 function CurriculumDataVo(data,teacherArr) {
    var self = this;     
    self.subjectTitle                              		=   ko.observable();
    self.isOptional                                		=   ko.observable();
    self.subjectId                              		=   ko.observable();
    self.aypId                           				=   ko.observable();
    self.subSubjects                        			=   ko.observableArray();
    self.planStatus                              		=   ko.observable();
    self.ceGradeId                        				=   ko.observable();
    self.cePeriodPerWeek                              	=   ko.observable();
    self.labPeriodPerWeek                              	=   ko.observable();
    self.ownerTeacherId                                	=   ko.observable();
    self.periodPerWeek                              	=   ko.observable();
    self.subjectType									=   ko.observable();

    self.teacherName								    = ko.computed(function() {
        var _teacherName
            var tempteacherName =  ko.utils.arrayForEach(teacherArr, function(item) {
            if(String(item.userId())==String(self.ownerTeacherId()))
            { 
                  _teacherName =  item.title()+" "+item.firstName()+" "+ item.lastName();
                 // _teacherName = [ item.firstName(), item.lastName(),item.userId()];
            }
         });
        return _teacherName;   
    }, this);     
      
    self.selectedItem							=	ko.observable();   
   
    
    
    self.cache = function() {};
    self.update(data,teacherArr)   
    
    
    
    
    
    
    
    
    
    
    
    
 }
 
 
 
 
 
//ko.utils.extend(CurriculumViewModel.prototype, {   });



ko.utils.extend(CurriculumViewModel.prototype, {
    //select an item and make a copy of it for editing
    selectItem: function(item) {
        console.log("::selectItem::",item);
        this.selectedItem(item);
        this.itemForEditing(new CurriculumVO(ko.toJS(item)));
    },
    
    acceptItem: function(item) {
        var selected = this.selectedItem(),
            edited = ko.toJS(this.itemForEditing()); //clean copy of edited
        
        //apply updates from the edited item to the selected item
        selected.update(edited);
        
        //clear selected item
        this.selectedItem(null);
        this.itemForEditing(null);
    },
    
    //just throw away the edited item and clear the selected observables
    revertItem: function() {
        this.selectedItem(null);
        this.itemForEditing(null);
    },
    //
    
});



ko.utils.extend(CurriculumVO.prototype, {
     update: function(data,teacherArr) {
     this.ceGradeId(data.ceGradeId || "");
     this.gradeTitle(data.gradeTitle || "");
    
     
     //console.log("ko.utils.extend(FormativeAssessmentVO.prototype||subSubjectsComboArr",subSubjectsComboArr);     
     
     
     if(data.data)
      {
    	 var mappedCurriculumData = jQuery.map(data.data, function(item) {
    	 	// console.log("mappedCurriculumData item",item)
            return new CurriculumDataVo(item,teacherArr)
        });
        this.data(mappedCurriculumData); 
     //console.log("mappedCurriculumData",mappedCurriculumData)
        //save off the latest data for later use
        this.cache.latestData = data;
        }
      },
      //select an item and make a copy of it for editing
       // selectItem: function(item,subSubjectsComboArr,toolsComboArr,techniquesComboArr,currentContent) {       
        //this.tests.selectedItem(item,subSubjectsComboArr,toolsComboArr,techniquesComboArr,currentContent);
       // this.itemForEditing(new ContentModel(ko.toJS(item),subSubjectsComboArr,toolsComboArr,techniquesComboArr));
    //},
    
    acceptItem: function(item) {
       // var selected = this.tests.selectedItem(),
       // edited = ko.toJS(this.itemForEditing()); //clean copy of edited      
       // selected.update(edited);
       // this.tests.selectedItem(null);
       // this.itemForEditing(null);
    },
    
    //just throw away the edited item and clear the selected observables
    revertItem: function() {
        //this.tests.selectedItem(null);
       // this.itemForEditing(null);
         this.update(this.cache.latestData);
    }     
});

ko.utils.extend(CurriculumDataVo.prototype, {
     update: function(data,teacherArr) {
     this.subjectTitle(data.subjectTitle || "");
     this.isOptional(data.isOptional || "");
     this.subjectId(data.subjectId || "");
     this.aypId(data.aypId || "");   
    // this.subSubjects(data.subSubjects || "");   
     this.planStatus(data.planStatus || ""); 
     this.ceGradeId(data.ceGradeId || "");      
     this.cePeriodPerWeek(data.cePeriodPerWeek || "");      
     this.labPeriodPerWeek(data.labPeriodPerWeek || "");  
   	 this.ownerTeacherId(data.ownerTeacherId || "");      
     this.periodPerWeek(data.periodPerWeek || ""); 
     this.subjectType(data.subjectType || ""); 
          
          
     if(data.subSubjects)
      {
    	 var mappedSubSubjectData = jQuery.map(data.subSubjects, function(item) {
    	 	console.log("mappedSubSubjectData item",item)
            return new CurriculumDataVo(item,teacherArr)
        });
        this.subSubjects(mappedSubSubjectData); 
     console.log("mappedSubSubjectData",mappedSubSubjectData)
        //save off the latest data for later use
        this.cache.latestData = data;
        }     
          
          
          
     /*if(data.childs)
      {
    	 var mappedRoomData = jQuery.map(data.childs, function(item) {
            return new RoomModelVo(item,currentContent)
        });
        this.childs(mappedRoomData);  
        
        this.cache.latestData = data;
        }*/
      },
   
    
    acceptItem: function(item) {    
    },
    
    //just throw away the edited item and clear the selected observables
    revertItem: function() {
        this.update(this.cache.latestData);
    }     
});

ko.utils.extend(TeacherVo.prototype, {
     update: function(data) {
     this.userId(data.userId || "");
	 this.title(data.title || "");
     this.firstName(data.firstName || "");
     this.middleName(data.middleName || "");   
     this.lastName(data.lastName || "");   
   	 //console.log("this.userId()---------------",this.userId())
      },
   
    
    acceptItem: function(item) {    
    },
    
    //just throw away the edited item and clear the selected observables
    revertItem: function() {
        this.update(this.cache.latestData);
    }     
});

//----------------------HELP INTEGRATION----------------------------------------
var isHelpActive = false;

function showHelp() {
    console.log("-------> showing help dialog");

    if (!isHelpActive) {
        isHelpActive = true;
        helpType = "teacher_defineFormativeAssessment";
        var active = "0"//$("#tabs").tabs("option", "active");
        help_scrollPosition = 'teacher_defineFormativeAssessment' + active;

        jQuery(".help").load("/ce-static-testedge/common/html/help.html", function() {
            //scrollTo('ayp_section_'+active);
            console.log('teacher_defineFormativeAssessment' + active);
        });

    } else {
        isHelpActive = false;
        jQuery(".help").empty();
    }
}
function closeHelpSection() {
    console.log("closing help section");
    isHelpActive = false;
    jQuery(".help").empty();
}



function retrunToAcademicYear(event) {	
	location.href = baseurl.replace("p_p_state=exclusive", "p_p_state=normal") + "getAcademics";
}


function changeBgscoTemBg(ref) {
	jQuery(preRefSco).css("background", "url(/ce-static-testedge/common/images/tabBg.png) repeat-x bottom");
	jQuery(ref).css("background", "url(/ce-static-testedge/common/images/tabActiveBg.png) repeat-x bottom");
	//$( ref ).tabs( "enable" );
	preRefSco = ref;
}

function changeBgscoTemBgDialog(ref) {
	jQuery(preRefScoAddSDia).css("background", "url(/ce-static-testedge/common/images/tabBg.png) repeat-x bottom");
	jQuery(ref).css("background", "url(/ce-static-testedge/common/images/tabActiveBg.png) repeat-x bottom");
	preRefScoAddSDia = ref;

	changeBgscoTemBg(jQuery("#tabs-2 .tabs2 li:nth-child(" + (Number(coScholObsModel.selectedTermIndex()) + 1) + ")"));
}




function changeTeacher(_url) {
	
	$.ajax({
		url : _url,
		type : "post",

		success : function(result) {
			console.log("teachers Saved", result);	
			window.setTimeout('location.reload()', 500); //reloads after 1/2 seconds
		},
		error : function(jqXHR, textStatus, errorThrown) {
			console.log("error");
		}
	});
}






